<template>
  <div class="main-header">
    <div class="left-section">
      <slot name="left"></slot>
    </div>
    
    <div class="center-section">
      <slot name="center"></slot>
    </div>
    
    <div class="right-section">
      <div class="header-actions">
        <n-tooltip trigger="hover" placement="bottom">
          <template #trigger>
            <n-button quaternary circle size="large" @click="toggleTheme">
              <template #icon>
                <n-icon>
                  <SunnyOutline v-if="isDarkTheme" />
                  <MoonOutline v-else />
                </n-icon>
              </template>
            </n-button>
          </template>
          {{ isDarkTheme ? '切换到亮色模式' : '切换到暗色模式' }}
        </n-tooltip>
        
        <n-tooltip trigger="hover" placement="bottom">
          <template #trigger>
            <n-button quaternary circle size="large" @click="openNotifications">
              <template #icon>
                  <div class="notification-badge-wrapper">
                    <n-badge 
                      :value="unreadNotificationsCount" 
                      :max="99" 
                      processing 
                      type="error"
                      :offset="[10, -5]"
                    >
                      <n-icon>
                        <NotificationsOutline />
                      </n-icon>
                    </n-badge>
                  </div>
              </template>
            </n-button>
          </template>
        </n-tooltip>
        
        <n-dropdown :options="userMenuOptions" @select="handleUserMenuSelect">
          <div class="user-avatar">
            <n-avatar v-if="userAvatar" round :src="userAvatar" />
            <n-avatar v-else round>{{ userInitials }}</n-avatar>
            <span v-if="showUsername" class="username">{{ username }}</span>
          </div>
        </n-dropdown>
      </div>
    </div>
    
    <n-drawer v-model:show="showNotifications" placement="right" width="360" :trap-focus="false">
      <n-drawer-content title="通知中心">
        <template #header>
          <div class="drawer-header">
            <span>通知中心</span>
            <n-button quaternary size="small" @click="clearAllNotifications">
              清空全部
            </n-button>
          </div>
        </template>
        
        <div class="notifications-container">
          <template v-if="notifications.length > 0">
            <div 
              v-for="notification in notifications" 
              :key="notification.id" 
              class="notification-item" 
              :class="{ 'unread': !notification.read }"
              @click="markNotificationAsRead(notification.id)"
            >
              <n-icon size="24" class="notification-icon" :color="getNotificationIconColor(notification.type)">
                <InformationCircleOutline v-if="notification.type === 'info'" />
                <CheckmarkCircleOutline v-else-if="notification.type === 'success'" />
                <WarningOutline v-else-if="notification.type === 'warning'" />
                <AlertCircleOutline v-else-if="notification.type === 'error'" />
              </n-icon>
              <div class="notification-content">
                <div class="notification-title">{{ notification.title }}</div>
                <div class="notification-message">{{ notification.content }}</div>
                <div class="notification-time">{{ formatTime(notification.timestamp) }}</div>
              </div>
            </div>
          </template>
          <n-empty v-else description="暂无通知" />
        </div>
      </n-drawer-content>
    </n-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, h } from 'vue'
import { useRouter } from 'vue-router'
import { useAppStore } from '../../stores/appStore'
import { useUserStore } from '../../stores/userStore'
import { storeToRefs } from 'pinia'
import { 
  NButton, 
  NIcon, 
  NTooltip, 
  NDropdown, 
  NAvatar, 
  NBadge, 
  NDrawer, 
  NDrawerContent,
  NEmpty 
} from 'naive-ui'
import type { DropdownOption } from 'naive-ui'
import { 
  MoonOutline, 
  SunnyOutline, 
  NotificationsOutline,
  SettingsOutline,
  LogOutOutline,
  PersonOutline,
  InformationCircleOutline,
  CheckmarkCircleOutline,
  WarningOutline,
  AlertCircleOutline
} from '@vicons/ionicons5'
import { DateUtils } from '../../utils/date'

// 属性定义
const props = defineProps({
  showUsername: {
    type: Boolean,
    default: true
  }
})

// Store引用
const router = useRouter()
const appStore = useAppStore()
const userStore = useUserStore()

// 从Store中提取响应式状态
const { isDarkTheme, notifications } = storeToRefs(appStore)
const { toggleTheme, markNotificationAsRead, clearNotifications } = appStore
const { currentUser } = storeToRefs(userStore)
const { logout } = userStore

// 计算属性
const username = computed(() => currentUser.value?.nickname || currentUser.value?.username || '未登录')
const userAvatar = computed(() => currentUser.value?.avatar || '')
const userInitials = computed(() => {
  const name = username.value
  if (!name || name === '未登录') return '游'
  return name.charAt(0)
})
const unreadNotificationsCount = computed(() => {
  return notifications.value.filter(n => !n.read).length
})

// 本地状态
const showNotifications = ref(false)

// 方法
const openNotifications = () => {
  showNotifications.value = true
}

const clearAllNotifications = () => {
  clearNotifications()
}

const handleUserMenuSelect = (key: string) => {
  switch (key) {
    case 'profile':
      router.push('/user-center')
      break
    case 'settings':
      router.push('/settings/general')
      break
    case 'logout':
      logout()
      router.push('/login')
      break
  }
}

const formatTime = (timestamp: number) => {
  return DateUtils.fromNow(timestamp)
}

const getNotificationIconColor = (type: string) => {
  switch (type) {
    case 'info':
      return '#2080f0'
    case 'success':
      return '#18a058'
    case 'warning':
      return '#f0a020'
    case 'error':
      return '#d03050'
    default:
      return '#2080f0'
  }
}

// 下拉菜单选项
const userMenuOptions = computed<DropdownOption[]>(() => [
  {
    key: 'profile',
    label: '个人中心',
    icon: () => h(PersonOutline)
  },
  {
    key: 'settings',
    label: '设置',
    icon: () => h(SettingsOutline)
  },
  {
    type: 'divider',
    key: 'd1'
  },
  {
    key: 'logout',
    label: '退出登录',
    icon: () => h(LogOutOutline)
  }
])
</script>

<style lang="scss" scoped>
.main-header {
  display: flex;
  align-items: center;
  height: 64px;
  padding: 0 16px;
  background-color: var(--component-background);
  border-bottom: 1px solid var(--border-color-base);
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  
  .left-section {
    flex: 1;
    display: flex;
    align-items: center;
  }
  
  .center-section {
    flex: 2;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .right-section {
    flex: 1;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    
    .header-actions {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .notification-badge-wrapper {
        position: relative;
        
        :deep(.n-badge) {
          .n-badge-sup {
            transform: translate(50%, -50%);
          }
        }
      }
    }
    
    .user-avatar {
      display: flex;
      align-items: center;
      cursor: pointer;
      padding: 4px 8px;
      border-radius: 4px;
      transition: background-color 0.2s;
      
      &:hover {
        background-color: rgba(0, 0, 0, 0.05);
      }
      
      .username {
        margin-left: 8px;
        font-size: 14px;
        max-width: 120px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}

.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.notifications-container {
  .notification-item {
    display: flex;
    padding: 12px 16px;
    border-bottom: 1px solid var(--border-color-base);
    cursor: pointer;
    transition: background-color 0.2s;
    
    &:hover {
      background-color: rgba(0, 0, 0, 0.03);
    }
    
    &.unread {
      background-color: rgba(0, 130, 255, 0.05);
      
      &:hover {
        background-color: rgba(0, 130, 255, 0.08);
      }
      
      .notification-title {
        font-weight: 600;
      }
    }
    
    .notification-icon {
      margin-right: 12px;
      flex-shrink: 0;
    }
    
    .notification-content {
      flex: 1;
      min-width: 0;
      
      .notification-title {
        font-size: 14px;
        margin-bottom: 4px;
      }
      
      .notification-message {
        font-size: 13px;
        color: var(--text-color-secondary);
        margin-bottom: 6px;
        word-break: break-word;
      }
      
      .notification-time {
        font-size: 12px;
        color: var(--text-color-secondary);
      }
    }
  }
}
</style>